package server;

import config.MongoDB;
import entities.TaEntity;
import entities.TaskEntity;


import java.io.*;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

//import json.ResultJson;

import json.ReplyJson;
import json.SearchResultJson;
import okhttp3.*;
import org.apache.log4j.Logger;

import java.io.IOException;

import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;



/**
 * Created by Yang Fan on 2017/12/13.
 */
public class TaskThread extends Thread {

    static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(500, TimeUnit.MILLISECONDS)
            .writeTimeout(500, TimeUnit.MILLISECONDS).readTimeout(500, TimeUnit.MILLISECONDS).build();//设置超时
    //    static OkHttpClient client = new OkHttpClient();
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private static final Logger logger = Logger.getLogger(ParseServer.class);


    BlockingQueue<TaskEntity> queue;
    public static String url;

    public Map TaEntitytable;


    public TaskThread(BlockingQueue queue, String url, Map TaEntity_table) {
        this.queue = queue;
        this.url = url;
        this.TaEntitytable=TaEntity_table;
    }

    //线程体  一切从run开始
    @Override
    public void run() {
        //线程体
        //从队列取
        boolean thread_control = true;


        while (thread_control) {

            ReplyJson results = new ReplyJson(); //每取一次任务，初始化一个ReplyJson
            results.setRtnCode("9999");        // 给ReplyJson初始值
            results.setRtnMsg("未知错误");
            TaskEntity task_exe = null;
            try {
                task_exe = queue.take(); //取任务

                String jsonString="";





                TaskExec exec = new RandomExec(task_exe);

                System.out.println(task_exe.getUuid());

                List<SearchResultJson> resultJsons = new ArrayList<>();


                try {
                    resultJsons = exec.run();
                } catch (Exception e) {
                    e.printStackTrace();
                    results.setRtnCode("1001");
                    results.setRtnMsg("任务执行出现错误");
                    return;
                }


                ObjectMapper mapper = new ObjectMapper();
                OutputStreamWriter fw = null;

                try {
                    fw = new OutputStreamWriter(new FileOutputStream(task_exe.getToFile(), false),"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    results.setRtnCode("1002");
                    results.setRtnMsg("写文件编码错误");
                    return;
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    results.setRtnCode("1003");
                    results.setRtnMsg("写入文件"+task_exe.getToFile()+"路径不存在");
                    return;
                }


                for (SearchResultJson resultJson:resultJsons){
                    jsonString = mapper.writeValueAsString(resultJson);
                    fw.write(jsonString+"\n");

                }


                fw.close();

                results.setRtnCode("0");
                results.setRtnMsg("转换成功");



            } catch (InterruptedException e) {
                e.printStackTrace();
                results.setRtnCode("1004");
                results.setRtnMsg("写文件编码错误");
            } catch (IOException e) {
                e.printStackTrace();
                results.setRtnCode("1005");
                results.setRtnMsg("写入文件失败");
            } finally {


                task_exe.setState(true);
                MongoDB.instance().getDatabase().save(task_exe);
                String resultStr = ParseServer.entityToJson(results);
                postMess(url,resultStr);


            }

        }








    }

    public static void postMess(String url, String json) {

        //POST提交Json数据
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            String resultStr = response.body().string();
            System.out.println(resultStr);
            logger.debug("after execute get result:{}" + resultStr);
        } catch (IOException e) {
            logger.error("HttpJob execute error! problem url:{}" + url, e);
        } finally {
            response.body().close();
        }
    }
}
